package advanced.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkClient implements Runnable {
    private boolean flg = true;
    private DatagramSocket client = null;
    private InetSocketAddress packetAddress = null;

    public TalkClient(int localPort, InetSocketAddress packetAddress) {
        //使用DatagramSocket 指定端口 创建发送端
        try {
            client = new DatagramSocket(localPort);
            this.packetAddress = packetAddress;
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        while (flg) {
            //准备数据  转成字节数组
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            try {
                line = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (line.equals("exit")) {
                System.out.println("客户端下线");
                try {
                    sendMsg(line.getBytes("UTF-8"), packetAddress, client);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                flg = false;
                return;
            }
            sendMsg(line.getBytes(), packetAddress, client);
            receiveMsg(client, packetAddress);

        }
    }

    private void sendMsg(byte[] data, InetSocketAddress address, DatagramSocket sender) {
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, address);
        try {
            sender.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String receiveMsg(DatagramSocket localClient, InetSocketAddress packetAddress) {
        byte[] container = new byte[100];
        DatagramPacket packet = new DatagramPacket(container, 0, container.length, packetAddress);
        String msg = "";
        try {
            localClient.receive(packet);
            msg = new String(packet.getData());
            System.out.println(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }

    public void stop() {
        flg = false;
        if (!client.isClosed()) client.close();
    }
}
